package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.asn1.axdr.AxdrEnum;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * TI类
 * 实现时间标识的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class TI implements AxdrType {

    private byte[] dataCode = null;
    private AxdrEnum unit = null;
    private Unsigned16 inter = null;

    /**
     * 默认构造函数
     */
    public TI() {
    }

    /**
     * 设置数据编码
     * 
     * @param dataCode 数据编码
     */
    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    /**
     * 设置时间标识参数
     * 
     * @param unit  单位
     * @param inter 间隔
     */
    public void setUnitInter(AxdrEnum unit, Unsigned16 inter) {
        this.unit = unit;
        this.inter = inter;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        int codeLength = 0;
        unit = new AxdrEnum();
        unit.setConst();
        codeLength += unit.decode(input);

        inter = new Unsigned16();
        inter.setConst();
        codeLength += inter.decode(input);
        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        int codeLength;
        if (dataCode != null) {
            codeLength = dataCode.length;
            for (int i = dataCode.length - 1; i >= 0; i--) {
                try {
                    output.write(dataCode[i]);
                } catch (java.io.IOException e) {
                    throw new RuntimeException(e);
                }
            }
        } else {
            if (unit != null && inter != null) {
                codeLength = 0;
                codeLength += inter.encode(output);
                codeLength += unit.encode(output);
            } else {
                throw new RuntimeException("encode error，unit or inter is null");
            }
        }
        return codeLength;
    }

    /**
     * 编码并保存
     * 
     * @param encodingSizeGuess 编码大小预估
     */
    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    /**
     * 获取单位
     * 
     * @return 单位
     */
    public AxdrEnum getUnit() {
        return unit;
    }

    /**
     * 获取间隔
     * 
     * @return 间隔
     */
    public Unsigned16 getInter() {
        return inter;
    }

    @Override
    public String toString() {
        if (unit != null && inter != null) {
            return "sequence: {" + "unit: " + unit + ", inter: " + inter + "}";
        } else {
            return "unit or inter is null";
        }
    }
}